package com.safe.app.config.init.redis;

import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import redis.clients.jedis.Protocol;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * redis 缓存 分布式锁 使用 redisson jar
 * 
 * @Autowired
 */
@Data
public class RedissonUtils {

	private static final String REDIS_NAME = "redis://";

	private static RedissonClient redissonClient = null;

	private String hostName = "localhost";

	private int port = Protocol.DEFAULT_PORT;

	private int database = 0;

	private int timeout = Protocol.DEFAULT_TIMEOUT;

	private String password;

	@PostConstruct
	void init() throws Exception {
		Config config = new Config();
		SingleServerConfig singleServerConfig = config.useSingleServer().setAddress(REDIS_NAME + hostName + ":" + port)
				.setDatabase(database).setTimeout(timeout);
		if (StringUtils.isNotBlank(password)){}
			singleServerConfig.setPassword(password);
		redissonClient = Redisson.create(config);
	}

	@PreDestroy
	void destroy() throws Exception {
		if (redissonClient != null) {
			redissonClient.shutdown();
		}
	}
}
